package cn.com.atlasdata.atops.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 公共方法
 *
 * @author ZJH
 * @create 2018-08-27 15:54
 **/
public class Util {
    private static final Logger log = LoggerFactory.getLogger(Util.class);
    //从请求request中获取json参数
    public static JSONObject getJsonParam(HttpServletRequest request){
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
//                line = line.replace("\\","");
                stringBuilder.append(line);
            }
            jsonParam = JSONObject.parseObject(stringBuilder.toString());
        } catch (Exception e) {
            log.error("解析json字符串发生异常",e);
        }
        return jsonParam;
    }

    //从请求request中获取json数组
    public static JSONArray getJsonParamList(HttpServletRequest request){
        List<JSONObject> jsonList= new ArrayList<JSONObject>();
        JSONArray parseArray = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                line = line.replace("\\","");
                stringBuilder.append(line);
            }
            parseArray =JSON.parseArray(stringBuilder.toString());
        } catch (Exception e) {
            log.error("解析json数组字符串发生异常",e);
        }
        return parseArray;
    }
}
